package cn.nxcoder.blog.service.impl;

import cn.nxcoder.blog.core.AbstractService;
import cn.nxcoder.blog.dao.BlogMapper;
import cn.nxcoder.blog.dao.TypeMapper;
import cn.nxcoder.blog.entity.Type;
import cn.nxcoder.blog.service.TypeService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * 博客类型Service
 * @author shengwu ni
 * @date 2018/05/05 15:33
 */
@Service
public class TypeServiceImpl extends AbstractService<Type> implements TypeService {

    @Resource
    private TypeMapper typeMapper;
    @Resource
    private BlogMapper blogMapper;

    @Override
    public List<Type> findTop6Types() {

        List<Type> types = typeMapper.selectAll();
        if (types != null && types.size() > 0) {
            if (types.size() <= 6) {
                return sortTypes(types);
            } else {
                return sortTypes(types).subList(0, 5);
            }
        }
        return null;
    }

    @Override
    public List<Type> findAllTypes() {
        List<Type> types = typeMapper.selectAll();
        if (types != null && types.size() > 0) {
            return sortTypes(types);
        }  else {
            return null;
        }
    }

    private List<Type> sortTypes(List<Type> types) {

        for (Type type : types) {
            Integer count = blogMapper.findCount(type.getId());
            type.setBlogNum(count);
        }

        // 根据Type类中的blogNum来排序
        types.sort((o1, o2) -> o2.getBlogNum().compareTo(o1.getBlogNum()));

        return types;
    }
}
